package com.weijin.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weijin.service.RedisService.MessageRankService;
import com.weijin.vo.RestResultVo;
import com.weijin.web.websocket.ChatAnnoHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Set;

/**
 * @Author WeiJin
 * @Version 1.0
 * @Date 2025/3/24 18:03
 */
@Component
@Slf4j
public class RedisMessageListener implements MessageListener {

    @Resource
    private ChatAnnoHandler chatAnnoHandler;
    @Resource
    private MessageRankService rankService;
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        // 获取信息
        String s = new String(message.getBody(), StandardCharsets.UTF_8);
        // 将消息发送给所有人
        chatAnnoHandler.sendAllMessage(s);
        //获取排行榜
        Set<ZSetOperations.TypedTuple<String>> rank = rankService.getTop10();
        RestResultVo<Object> resultVo = new RestResultVo<>();
        resultVo.setStatus(2001);
        resultVo.setData(rank);
        String strRank = null;
        try {
            strRank = objectMapper.writeValueAsString(resultVo);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        //将排行榜广播给所有人
        chatAnnoHandler.sendAllMessage(strRank);
        log.info("[订阅消息]: 监听到消息：{}", s);
    }
}
